﻿using DAL;
using DAL.DBManagers;
using DAL.Models;
using System;

public partial class UserEdit : System.Web.UI.Page
{
    Guid UserID = Guid.Empty;
    UsersManager manager = new UsersManager();

    protected void Page_Load(object sender, EventArgs e)
    {
        if (Guid.TryParse(Request.QueryString["id"], out UserID))
        {
            if (!IsPostBack)
            {
                var user = manager.Single(s => s.UserID == UserID);

                txtUserName.Text = user.UserName;
                txtFullName.Text = user.FullName;
            }
        }
    }

    protected void btnSave_Click(object sender, EventArgs e)
    {
        if (UserID == Guid.Empty)
        {
            manager.Add(new User
            {
                UserID = Guid.NewGuid(),
                UserName = txtUserName.Text,
                Password = HelperService.GetMd5Hash("Aa1@3456"),
                FullName = txtFullName.Text,
                IsActive = true,
                CreateDate = DateTime.Now,
                CreatedBy = (Session["User"] as UserHelper).UserID
            });
        }
        else
        {
            var user = manager.Single(s => s.UserID == UserID);

            user.UserName = txtUserName.Text;
            user.FullName = txtFullName.Text;
            user.LastModifyDate = DateTime.Now;
            user.LastModifier = (Session["User"] as UserHelper).UserID;
        }

        manager.SaveChanges();
        Response.Redirect("userview.aspx?m=liUsers");
    }
}